﻿using System;
using System.Collections;
using System.Xml;
using System.Text;
using InfoJetSoft.Service.Entity;
using InfoJetSoft.Service.Util;

namespace InfoJetSoft.Service.Worker
{

	class FormBuildXmlToEditFieldsWorker
	{
		
		public static void buildXmlToEditFields(Form form)
		{
			ArrayList xmlToEditFieldList = new ArrayList();
			StringBuilder nameBuffer = new StringBuilder();
			ArrayList xmlToEditList = form.Manifest.XmlToEditList;
			foreach (XmlToEdit xmlToEdit in xmlToEditList)
			{
				//CID 0543 //2010.04.30 //if
				if( xmlToEdit.ViewName.Equals( form.View.Name ) )
				{
					string component = xmlToEdit.Component;
					if (component.Equals(JetConstant.CMP_xOptional) || 
						component.Equals(JetConstant.CMP_xCollection) || 
						component.Equals(JetConstant.CMP_xReplace) ||
						component.Equals(JetConstant.CMP_xFileAttachment) )
					{
						buildFieldsByXmlToEdit(xmlToEditFieldList, xmlToEdit, form);
						nameBuffer.Append(xmlToEdit.Name + JetConstant.ID_SEPARATOR);
					}
				}
			}
			string xmlToEditNames = nameBuffer.ToString();
			if (xmlToEditNames.EndsWith(JetConstant.ID_SEPARATOR))
			{
				xmlToEditNames = xmlToEditNames.Substring(0, xmlToEditNames.Length - 1);
			}
			Field namesField = new Field(JetConstant.XDOC_DATA_XMLTOEDIT_NAME_ARRAY, xmlToEditNames);
			xmlToEditFieldList.Add(namesField);
			form.XmlToEditFieldList = xmlToEditFieldList;
		}
		
		private static void  buildFieldsByXmlToEdit(ArrayList xmlToEditFieldList, XmlToEdit xmlToEdit, Form form)
		{
			string container = xmlToEdit.Container;
			string containerIdArray = "";
			if( container.Length > 0 ) //for FileAttachment
			{
				containerIdArray = buildIdArray(container, form);
			}
			Field containerField = new Field(xmlToEdit.Name + "_container", containerIdArray);
			xmlToEditFieldList.Add(containerField);
			
			string item = xmlToEdit.Item;
			string itemIdArray = "";
			if( item.Length > 0 ) //for FileAttachment
			{
				itemIdArray = buildIdArray(item, form);
			}
			Field itemField = new Field(xmlToEdit.Name + "_item", itemIdArray);
			xmlToEditFieldList.Add(itemField);
		}
		
		private static string buildIdArray(string filter, Form form)
		{
			XmlElement root = form.XmlDoc.DocumentElement;
			
			StringBuilder idBuffer = new StringBuilder();
			XmlNodeList nodeList = DOMUtil.selectNodes(root, filter, 0, form.XmlNsResolver);
			for (int i = 0; i < nodeList.Count; i ++ )
			{
				XmlNode node = (XmlNode) nodeList[ i ];
				string id = DOMUtil.getNodeJetId(node);
				idBuffer.Append(id);
				if (i < nodeList.Count - 1)
				{
					idBuffer.Append(JetConstant.ID_SEPARATOR);
				}
			}
			
			return idBuffer.ToString();
		}
	}
}